package com.uinnova.product.eam.service.es;

import com.binary.core.util.BinaryUtils;
import org.springframework.util.CollectionUtils;
import com.alibaba.fastjson.JSONObject;
import com.uinnova.product.eam.comm.model.es.AppSquareConfig;
import com.uino.bean.permission.business.request.BusinessConfigDto;
import com.uino.dao.AbstractESBaseDao;
import com.uino.service.util.FileUtil;
import com.uino.util.digest.impl.type.Base64Util;
import com.uino.util.sys.CommonFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author bingshen
 * @Classname AppSquareConfigDao
 * @Date 2022/5/25 14:23
 */
@Service
@Slf4j
public class AppSquareConfigDao extends AbstractESBaseDao<AppSquareConfig, AppSquareConfig> {
    @Override
    public String getIndex() {
        return "uino_eam_square_config";
    }

    @Override
    public String getType() {
        return getIndex();
    }
    @PostConstruct
    public void init() {
        List<AppSquareConfig> list = FileUtil.getData("/initdata/uino_eam_square_config.json", AppSquareConfig.class);

        List<AppSquareConfig> newList = list;
        // 判断文件是否存在
        URL resource = this.getClass().getClassLoader().getResource("./initdata/uino_business_config.json");
        if (resource != null) {
            List<String> businessConfigList = CommonFileUtil.getData("/initdata/uino_business_config.json", String.class);
            // 存在就过滤可用配置
            if (!CollectionUtils.isEmpty(businessConfigList)) {
                String result = businessConfigList.get(0);
                String content = Base64Util.base64dec(result);
                BusinessConfigDto businessConfigDto = JSONObject.parseObject(content, BusinessConfigDto.class);
                if (businessConfigDto != null && !CollectionUtils.isEmpty(businessConfigDto.getSquareConfig())) {
                    // 先删除初始化进去的系统模块数据
                    BoolQueryBuilder builder = QueryBuilders.boolQuery();
                    builder.must(QueryBuilders.termQuery("isInit", 0));
                    deleteByQuery(builder, true);

                    // 从功能配置读取数据
                    List<Long> configIdList = businessConfigDto.getSquareConfig();
                    list = list.stream().filter(appSquareConfig -> configIdList.contains(appSquareConfig.getId())).collect(Collectors.toList());
                    if (CollectionUtils.isEmpty(list)) {
                        list = newList;
                    }
                }
            }
        }
        try {
            RestHighLevelClient clientc = getClient();
            GetIndexRequest getRequest = new GetIndexRequest();
            String fullIndexName = getFullIndexName();
            getRequest.indices(fullIndexName);
            boolean existIndex = clientc.indices().exists(getRequest, RequestOptions.DEFAULT);
            if (!existIndex) {
                CreateIndexRequest createIndex = new CreateIndexRequest(getFullIndexName());
                createIndex.settings(getSetting("my-analyzer", 1));
                createIndex.mapping(getFullTypeName(), getMapping("my-analyzer"));
                clientc.indices().create(createIndex, RequestOptions.DEFAULT);
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("index.mapping.total_fields.limit", 2000);
                map.put("index.max_result_window", 100000000);
                UpdateSettingsRequest updateSettingsRequest = new UpdateSettingsRequest(getFullIndexName());
                updateSettingsRequest.settings(map);
                clientc.indices().putSettings(updateSettingsRequest, RequestOptions.DEFAULT);
                saveOrUpdateBatch(list);
            } else {
                // 更新地址/eam#/appWall/BusData/1为/diagram#/fullview
                List<AppSquareConfig> listByQuery = getListByQuery(QueryBuilders.boolQuery());
                List<AppSquareConfig> updateAppSquareList = new ArrayList<>();
                for (AppSquareConfig appSquareConfig : listByQuery) {
                    if (!BinaryUtils.isEmpty(appSquareConfig) && !BinaryUtils.isEmpty(appSquareConfig.getAddressLink())
                            && "/eam#/appWall/BusData/1".equals(appSquareConfig.getAddressLink())) {
                        appSquareConfig.setAddressLink("/diagram#/fullview");
                        updateAppSquareList.add(appSquareConfig);
                    }
                }
                if (!CollectionUtils.isEmpty(updateAppSquareList)) {
                    saveOrUpdateBatch(updateAppSquareList);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
